package com.components.base.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import com.components.base.action.BundleAction
import com.components.base.action.ClickAction
import com.components.base.action.HandlerAction
import com.components.base.ui.activity.BaseActivity
import java.util.*

abstract class BaseFragment<A : BaseActivity> : Fragment(), BundleAction, ClickAction, HandlerAction {

    /**父Activity对象*/
    private var mActivity: A? = null

    /**根布局*/
    private var mRootView: View? = null

    /**当前是否加载过*/
    private var mLoading: Boolean = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = requireActivity() as A
    }

    override fun onDetach() {
        removeCallbacks()
        mActivity = null
        super.onDetach()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mLoading = false
        return if (getLayoutId() > 0) {
            mRootView = inflater.inflate(getLayoutId(), null)
            mRootView
        } else {
            null
        }
    }

    override fun onDestroyView() {
        mLoading = false
        mRootView = null
        super.onDestroyView()
    }

    override fun onResume() {
        super.onResume()
        if (!mLoading) {
            mLoading = true
            initFragment()
        }
    }

    /**
     * 这个 Fragment 是否已经加载过了
     */
    fun isLoading(): Boolean {
        return mLoading
    }

    override fun getView(): View? {
        return mRootView
    }

    /**
     * 获取绑定的 Activity，防止出现 getActivity 为空
     */
    fun getAttachActivity(): A {
        return mActivity!!
    }

    open fun initFragment() {
        initView()
        initData()
    }

    /**
     * 获取布局 ID
     */
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化控件
     */
    protected abstract fun initView()

    /**
     * 初始化数据
     */
    protected abstract fun initData()

    /**
     * 根据资源 id 获取一个 View 对象
     */
    override fun <V : View> findViewById(@IdRes id: Int): V {
        return mRootView!!.findViewById(id)
    }

    override fun bundle(): Bundle? {
        return arguments
    }

    /**
     * startActivityForResult 方法优化
     */
    private var mActivityCallback: BaseActivity.OnActivityCallback? = null
    private var mActivityRequestCode = 0

    fun startActivityForResult(clazz: Class<out Activity?>?, callback: BaseActivity.OnActivityCallback?) {
        startActivityForResult(Intent(mActivity, clazz), null, callback)
    }

    fun startActivityForResult(intent: Intent?, callback: BaseActivity.OnActivityCallback?) {
        startActivityForResult(intent, null, callback)
    }

    fun startActivityForResult(intent: Intent?, options: Bundle?, callback: BaseActivity.OnActivityCallback?) {
        // 回调还没有结束，所以不能再次调用此方法，这个方法只适合一对一回调，其他需求请使用原生的方法实现
        if (mActivityCallback == null) {
            mActivityCallback = callback
            // 随机生成请求码，这个请求码必须在 2 的 16 次幂以内，也就是 0 - 65535
            mActivityRequestCode = Random().nextInt(Math.pow(2.0, 16.0).toInt())
            startActivityForResult(intent, mActivityRequestCode, options)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (mActivityCallback != null && mActivityRequestCode == requestCode) {
            mActivityCallback?.onActivityResult(resultCode, data)
            mActivityCallback = null
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    /**
     * 销毁当前 Fragment 所在的 Activity
     */
    fun finish() {
        if (mActivity != null && !mActivity!!.isFinishing) {
            mActivity!!.finish()
        }
    }

    /**
     * Fragment 返回键被按下时回调
     */
    fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 默认不拦截按键事件，回传给 Activity
        return false
    }

}